/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import com.google.gson.Gson;
import local.ThemeFacadeLocal;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Theme;
import javax.ejb.EJB;
import util.JsonReturnMsg;
import util.JsonReturnTable;

/**
 *
 * @author karennyq
 */
@WebServlet(name = "ThemeServlet", urlPatterns = {"/ThemeServlet"})
public class ThemeServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @EJB
    ThemeFacadeLocal themeFacade;
    Gson gson = new Gson();
    private String json;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        try {
            if (action.equals("getThemes")) {
                getThemes(request, response);

            } else if (action.equals("loadTable")) {
                loadTable(request, response);

            } else if (action.equals("updateTheme")) {
                updateTheme(request, response);

            } else if (action.equals("getThemeInfo")) {
                getThemeInfo(request, response);
            }

        } catch (Exception ex) {
            json = gson.toJson(new JsonReturnMsg("Error", ex.getMessage(), "error"));
            response.getWriter().println(json);
        } finally {
            response.getWriter().close();
        }
    }

    private void loadTable(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String industryId = (request.getParameter("industryId") != null) ? request.getParameter("industryId") : "";

        if (!industryId.equals("")) {
            Long ind_id = Long.parseLong(industryId);
            ArrayList<Theme> themeList = new ArrayList(themeFacade.getThemes(ind_id));
            ArrayList<Theme> sortThemeList = new ArrayList();
            Integer i = 1;
            while (i < 10) {
                for (Theme t : themeList) {
                    if (t.getPosition().equals(i)) {
                        sortThemeList.add(t);
                        break;
                    }
                }
                i++;
            }
            int totalRecord = sortThemeList.size();
            json = gson.toJson(new JsonReturnTable(totalRecord + "", themeList));
        } else {
            json = gson.toJson(new JsonReturnTable(0 + "", new ArrayList<Theme>()));
        }
        response.getWriter().println(json);
    }

    private void updateTheme(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String theme_id = (request.getParameter("theme_id") != null) ? request.getParameter("theme_id") : "";
        String theme_name = request.getParameter("theme_name");
        String short_desc = request.getParameter("theme_desc");
        String firm_qns = request.getParameter("theme_firm_qns");
        String ind_qns = request.getParameter("theme_ind_qns");
        if (!theme_id.equals("")) {
            Long themeId = Long.parseLong(theme_id);
            Theme t = themeFacade.updateTheme(themeId, theme_name, short_desc, firm_qns, ind_qns);
            json = gson.toJson(new JsonReturnMsg("Edit Theme", "Theme updated", "info"));
        } else {
            json = gson.toJson(new JsonReturnMsg("Edit Theme", "Theme does not exist", "error"));
        }
        response.getWriter().println(json);
    }

    private void getThemeInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String theme_id = (request.getParameter("theme_id") != null) ? request.getParameter("theme_id") : "";
        if (!theme_id.equals("")) {
            Long themeId = Long.parseLong(theme_id);
            Theme t = themeFacade.getTheme(themeId);
            json = gson.toJson(t);
        } else {
            json = gson.toJson(new JsonReturnMsg("Edit Theme", "Theme does not exist", "error"));
        }
        response.getWriter().println(json);
    }

    private void getThemes(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String industry = request.getParameter("industry");

        ArrayList<Theme> tList = themeFacade.getThemes(Long.parseLong(industry));

        response.setContentType("application/xml");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("<themelist>");

        for (Theme t : tList) {
            response.getWriter().write("<theme>");
            response.getWriter().write("<theme_id>" + t.getId() + "</theme_id>");
            response.getWriter().write("<theme_name>" + t.getName() + "</theme_name>");
            response.getWriter().write("</theme>");
        }
        response.getWriter().write("</themelist>");
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
